import React, { PureComponent, createRef } from "react";
import {
  Row,
  Table,
  Pagination,
  Typography,
  Button,
  Checkbox,
  message,
  Select,
  Form,
  Input,
  Modal,
  DatePicker,
  InputNumber
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { _ } from "lodash";
import moment from "moment";
import { createTenant, listTenants } from "../../services/tenant";
import styles from "./index.less";
import { TenantRights, getTenantRights } from "@/consts/consts";

class Tenant extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      total: 0,
      currentPage: 1,
      size: 10,
      dataSource: [],
      query: 0,
      isReady: false,
      tenantFormModalVisible: false
    };

    this.searchFormRef = createRef();
    this.tenantFormRef = createRef();
    this.tableWrapperRef = createRef();
    this.otherHeight = 0;
  }

  componentDidMount() {
    this.fetchTableData().finally(() => this.setState({ isReady: true }));
  }

  fetchTableData = async () => {
    const { size, currentPage } = this.state;
    const { name } = this.getSearchFormValue();

    const {
      data: { ret },
      data: {
        data: { list, total, query }
      }
    } = await listTenants({ size, page: currentPage, name });

    if (ret !== 0) {
      return;
    }
    this.setState({ total, dataSource: list, query });
  };

  handlePageChange = (page, size) => {
    this.setState({ currentPage: page, size }, this.fetchTableData);
  };

  cereateTenant = () => {
    this.setState({
      tenantFormModalVisible: true
    });
  };

  changeTenantStatus = () => {
    // todo
  };

  deleteProject = () => {
    // todo
  };

  // 生成table需要的columns
  spawnColumns = () => [
    {
      title: "租户名称",
      dataIndex: "name",
      key: "name",
      width: 300,
      fixed: "left"
    },
    {
      title: "创建日期",
      dataIndex: "createTime",
      key: "createTime",
      width: 200,
      render: (value) => moment.unix(value).format("YYYY-MM-DD H:mm:ss")
    },
    {
      title: "到期日期",
      dataIndex: "deadTime",
      key: "deadTime",
      width: 200,
      render: (value) => moment.unix(value).format("YYYY-MM-DD H:mm:ss")
    },
    {
      title: "禁用租户",
      dataIndex: "visible",
      key: "visible",
      width: 100,
      render: (value, record) => (
        <Checkbox checked={value} onClick={() => this.changeTenantStatus(record.id)} />
      )
    },
    {
      title: "租户状态",
      width: 100,
      dataIndex: "status",
      key: "status",
      render: (value, record) => {
        if (record.visible) {
          return <span style={{ color: "#22A800" }}>正常</span>;
        }
        return <span style={{ color: "#D9001B" }}>禁用</span>;
      }
    },
    {
      title: "等级",
      dataIndex: "showResult",
      width: 100,
      key: "showResult",
      render: (value) => getTenantRights(value) || "未知"
    },
    {
      title: "账号数量",
      dataIndex: "numbers",
      width: 100,
      key: "numbers"
    },
    {
      title: "操作",
      dataIndex: "operations",
      width: 200,
      key: "operations",
      render: (value, record) => (
        <Row>
          <Button
            type="primary"
            className="custom-edit-button"
            disabled={_.isEmpty(record.files)}
            onClick={() => {
              //
            }}
          >
            查看
          </Button>
          <Button
            type="primary"
            className="custom-edit-button"
            disabled={_.isEmpty(record.files)}
            onClick={() => {
              //
            }}
          >
            查看
          </Button>
        </Row>
      )
    }
  ];

  // 生成table需要的columns
  spawnSubColumns = () => [
    {
      title: "序号",
      dataIndex: "sn",
      key: "sn",
      width: 80,
      render: (value, record, index) => index + 1
    },
    {
      title: "账号",
      dataIndex: "phone",
      key: "phone",
      width: 200
    },
    {
      title: "角色类型",
      dataIndex: "roleType",
      key: "roleType",
      width: 200
    },
    {
      title: "操作",
      dataIndex: "operations",
      width: 100,
      key: "operations",
      render: (value, record) => (
        <Row>
          <Button
            type="primary"
            className="custom-edit-button"
            disabled={_.isEmpty(record.files)}
            onClick={() => {
              //
            }}
          >
            解除绑定
          </Button>
        </Row>
      )
    }
  ];

  resetFliter = () => {
    // todo
  };

  search = () => {
    this.fetchTableData();
  };

  renderRightsOptions = () => TenantRights.map((item) => (
    <Select.Option value={item.val} key={item.val}>
      {item.name}
    </Select.Option>
  ));

  getSearchFormValue = () => {
    const { getFieldsValue } = this.searchFormRef.current;
    const { name } = getFieldsValue();
    return { name };
  };

  getTenantFormValue = () => {
    const { getFieldsValue } = this.tenantFormRef.current;
    const {
      name, deadTime, rights, numbers
    } = getFieldsValue();
    return {
      name,
      deadTime,
      rights,
      numbers
    };
  };

  handleSaveTenantInfo = () => {
    const {
      name, deadTime, rights, numbers
    } = this.getTenantFormValue();
    createTenant({
      name,
      deadTime: deadTime.unix(),
      rights,
      numbers
    }).then((tenantRes) => {
      if (tenantRes.data.ret === 0) {
        message.success("创建成功！");
        this.setState({
          tenantFormModalVisible: false
        });
      } else {
        message.success("创建失败");
      }
    });
  };

  renderTenantFormModal = () => {
    const { tenantFormModalVisible } = this.state;
    return (
      <Modal
        centered
        title="新建租户"
        visible={tenantFormModalVisible}
        onOk={() => this.handleSaveTenantInfo()}
        onCancel={() => this.setState({ tenantFormModalVisible: false })}
      >
        <Form
          ref={this.tenantFormRef}
          labelCol={{
            span: 8
          }}
          wrapperCol={{
            span: 16
          }}
        >
          <Form.Item
            name="name"
            label="租户名称："
            rules={[{ required: true, message: "请输入租户名称" }]}
          >
            <Input placeholder="请输入" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item
            name="deadTime"
            label="到期日期"
            rules={[{ required: true, message: "请选择到期日期" }]}
          >
            <DatePicker placeholder="请选择" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item
            name="rights"
            label="等级"
            rules={[{ required: true, message: "请选择租户等级" }]}
          >
            <Select
              // showSearch
              placeholder="请选择"
              style={{ width: 200 }}
            >
              {this.renderRightsOptions()}
            </Select>
          </Form.Item>
          <Form.Item
            name="numbers"
            label="账号数量"
            rules={[{ required: true, message: "请输入租户数量" }]}
          >
            <InputNumber placeholder="请输入" style={{ width: 200 }} />
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  render() {
    const {
      total, dataSource, currentPage, isReady, size, query
    } = this.state;

    return (
      <div>
        <div className={styles["content-wrapper"]}>
          <h1>
            <span>租户管理</span>
          </h1>
          <div style={{ height: 10 }} />
          <Form ref={this.searchFormRef} className={styles.formLabel}>
            <Row>
              <Form.Item name="name" label="租户名称：">
                <Input style={{ width: 200 }} placeholder="请输入" />
              </Form.Item>
              <div style={{ width: 80 }} />
              <Button
                type="button"
                className="custom-edit-button"
                onClick={() => this.resetFliter()}
              >
                重置
              </Button>
              <div style={{ width: 10 }} />
              <Button type="primary" className="btn-green" onClick={() => this.search()}>
                查询
              </Button>
              <div style={{ width: 10 }} />
            </Row>
          </Form>
        </div>
        <div className={styles["content-wrapper"]}>
          <Row justify="space-between" align="middle" className="margin-TB10px">
            <span>租户列表</span>
            <div>
              <Button type="primary" onClick={() => this.cereateTenant()} className="btn-green">
                <PlusOutlined />
                新建
              </Button>
            </div>
          </Row>
          <Row ref={this.tableWrapperRef} className={styles.table}>
            <Table
              pagination={false}
              className="table-flex-height"
              loading={!isReady}
              dataSource={dataSource}
              columns={this.spawnColumns()}
              expandable={{
                expandedRowRender: ({ accounts }) => (
                  <>
                    <Table columns={this.genSubColumns} dataSource={accounts} pagination={false} />
                  </>
                )
              }}
              bordered={false}
              scroll={{
                x: 1300,
                y: 1000
              }}
              rowKey="_id"
            />
          </Row>

          <Row justify="space-between" align="middle" className={styles["table-bottom"]}>
            <Typography.Text>
              共
              {query}
              条记录 第
              {currentPage}
              /
              {' '}
              {Math.ceil(query / size) || 1}
              页
            </Typography.Text>

            <Pagination
              showQuickJumper
              showLessItems
              total={total}
              pageSize={10}
              current={currentPage}
              showSizeChanger={false}
              onChange={this.handlePageChange}
            />
          </Row>
        </div>
        {this.renderTenantFormModal()}
      </div>
    );
  }
}

export default Tenant;
